package com.ruoyi.order.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.customer.domain.CustomerFinance;
import com.ruoyi.customer.domain.CustomerUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MyUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.customer.domain.CustomerDistribution;
import com.ruoyi.customer.service.ICustomerDistributionService;
import com.ruoyi.customer.service.ICustomerFinanceService;
import com.ruoyi.customer.service.ICustomerStaticService;
import com.ruoyi.customer.service.ICustomerUserService;
import com.ruoyi.employee.domain.EmployeeFinance;
import com.ruoyi.employee.domain.EmployeeGift;
import com.ruoyi.employee.domain.EmployeeUser;
import com.ruoyi.employee.service.IEmployeeFinanceService;
import com.ruoyi.employee.service.IEmployeeGiftService;
import com.ruoyi.employee.service.IEmployeeStaticService;
import com.ruoyi.employee.service.IEmployeeUserService;
import com.ruoyi.market.domain.Level;
import com.ruoyi.market.service.ILevelService;
import com.ruoyi.order.domain.OrderGift;
import com.ruoyi.order.mapper.OrderGiftMapper;
import com.ruoyi.order.service.IOrderGiftService;
import com.ruoyi.thirdpart.service.IBizWechatPayService;
import com.ruoyi.thirdpart.service.IWxOAuthchatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 礼物订单 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class OrderGiftServiceImpl implements IOrderGiftService
{
    @Autowired
    private OrderGiftMapper orderGiftMapper;

    @Autowired
    private ICustomerUserService customerUserService;

    @Autowired
    private IEmployeeUserService employeeUserService;

    @Autowired
    private IEmployeeStaticService employeeStaticService;

    @Autowired
    private IEmployeeFinanceService employeeFinanceService;

    @Autowired
    private IEmployeeGiftService employeeGiftService;

    @Autowired
    private ILevelService levelService;

    @Autowired
    private IWxOAuthchatService wxOAuthchatService;

    @Autowired
    private ICustomerStaticService customerStaticService;

    @Autowired
    private ICustomerFinanceService customerFinanceService;

    @Autowired
    private ICustomerDistributionService customerDistributionService;

    @Autowired
    private IBizWechatPayService bizWechatPayService;

    @Autowired
    protected Validator validator;

    /**
     * 根据条件分页查询礼物订单列表
     *
     * @param orderGift 礼物订单信息
     * @return 礼物订单信息集合信息
     */
    @Override
    public List<OrderGift> selectOrderGiftList(OrderGift orderGift)
    {
        return orderGiftMapper.selectOrderGiftList(orderGift);
    }

    /**
     * 通过礼物订单编号查询礼物订单
     *
     * @param orderNo 礼物订单编号
     * @return 礼物订单对象信息
     */
    @Override
    public OrderGift selectOrderGiftByOrderNo(String orderNo)
    {
        return orderGiftMapper.selectOrderGiftByOrderNo(orderNo);
    }

    /**
     * 查询礼物订单总数汇总 - 条数
     *
     * @param orderGift 礼物订单信息
     * @return 礼物订单对象信息
     */
    @Override
    public int selectOrderGiftCountTotal(OrderGift orderGift)
    {
        return orderGiftMapper.selectOrderGiftCountTotal(orderGift);
    }

    /**
     * 查询礼物订单每日新增总数 - 条数
     *
     * @param orderGift 礼物订单信息
     * @return 礼物订单对象信息
     */
    @Override
    public List<Map<String, Object>> selectOrderGiftCountDaily(OrderGift orderGift)
    {
        return orderGiftMapper.selectOrderGiftCountDaily(orderGift);
    }


    /**
     * 查询礼物订单总数汇总 - 金额
     *
     * @param orderGift 礼物订单信息
     * @return 礼物订单对象信息
     */
    @Override
    public BigDecimal selectOrderGiftAmountTotal(OrderGift orderGift)
    {
        return orderGiftMapper.selectOrderGiftAmountTotal(orderGift);
    }

    /**
     * 查询礼物订单每日新增总数 - 金额
     *
     * @param orderGift 礼物订单信息
     * @return 礼物订单对象信息
     */
    @Override
    public List<Map<String, Object>> selectOrderGiftAmountDaily(OrderGift orderGift)
    {
        return orderGiftMapper.selectOrderGiftAmountDaily(orderGift);
    }

    /**
     * 新增保存礼物订单信息
     *
     * @param orderGift 礼物订单信息
     * @return 结果
     */
    @Override
    @Transactional
    public OrderGift insertOrderGift(OrderGift orderGift)
    {
        // 总价
        Long userId = SecurityUtils.getUserId();
        String orderNo = MyUtils.getOrderNoByTimeAndId(userId);

        CustomerUser customerUser = customerUserService.selectUserById(userId);

        orderGift.setShopId(customerUser.getShopId());
        orderGift.setAppId(customerUser.getAppId());
        orderGift.setOrderNo(orderNo);
        orderGift.setOrderUserId(userId);
        orderGift.setInitAmount(orderGift.getActualAmount());
        orderGiftMapper.insertOrderGift(orderGift);

        if(orderGift.getPayType().equals("balance")){
            // 余额支付
            if(customerUser.getBalance().compareTo(orderGift.getActualAmount()) == -1){
                throw new ServiceException("客户下单失败：可用余额不足");
            }
            if(StringUtils.isNotEmpty(orderGift.getWxId())){
                customerUser.setWxId(orderGift.getWxId());
            }
            // 扣减客户的余额
            customerUser.setBalance(customerUser.getBalance().subtract(orderGift.getActualAmount()));
            customerUserService.updateUserMoney(customerUser);
            settleCenter(orderGift);
        }else if(orderGift.getPayType().equals(UserConstants.PAY_TYPE_WX_OFFICIAL_ACCOUNT)){
            // 使用微信公众号支付
            CustomerUser cu = customerUserService.selectUserById(userId);
            BigDecimal yibai = new BigDecimal("100");
            float actualAmount = orderGift.getActualAmount().multiply(yibai).intValue();
            // totalFee 必须要以分为单位
            Object createOrderResult = bizWechatPayService.createOrder("打赏店员", orderNo, (int) actualAmount,
                    cu.getOpenId(), UserConstants.PAY_TYPE_WX_OFFICIAL_ACCOUNT, UserConstants.FINANCE_GIFT, orderGift.getShopId());
            orderGift.setPayParams(createOrderResult);
        }

        return orderGift;
    }


    // 结算中心
    @Override
    public void settleCenter(OrderGift orderGift){

        CustomerUser customerUser = customerUserService.selectUserById(orderGift.getOrderUserId());

        // 店员提成比例
        int rate = 1; // 比例
        Map<String, Object> map = new HashMap<>();
        map.put("orderUserId", orderGift.getOrderUserId());
        map.put("employeeUserId", orderGift.getEmployeeUserId());
        EmployeeUser employeeUser = employeeUserService.selectUserById(orderGift.getEmployeeUserId());
        Level level = levelService.selectLevelById(employeeUser.getUserLevel());
        int count = orderGiftMapper.selectOrderGiftCountTotal(orderGift);
        if(count > 1){
            // 续单
            rate = level.getContinueRewardCommissionRate();
        }else{
            // 首单
            rate = level.getFirstRewardCommissionRate();
        }
        // 店员实际获得金额
        BigDecimal employeeGetMoney = orderGift.getInitAmount().multiply(new BigDecimal(rate)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
        orderGift.setEmployeeGetAmount(employeeGetMoney);
        orderGift.setFinalAmount(orderGift.getInitAmount().subtract(employeeGetMoney));

        // 有邀请用户 - 该邀请用户是否分销
        if(StringUtils.isNotNull(customerUser.getInviteId())){
            CustomerDistribution customerDistribution = customerDistributionService.selectUserById(customerUser.getInviteId());
            // 有邀请用户，并且是分销者，并且状态正常 且分销模式是提成CPS
            if(StringUtils.isNotNull(customerDistribution) && customerDistribution.getActive().equals(UserConstants.ZERO) && customerDistribution.getDistributionModel().equals(UserConstants.CPS)){
                customerDistributionService.updateUserOrder(customerDistribution, orderGift.getInitAmount());
                // 订单设置分销员
                orderGift.setDistributionUserId(customerUser.getInviteId());
                orderGift.setIsDistribution(UserConstants.YES);

                // 设置舍入模式，这里使用四舍五入，并保留两位小数  获得的收益
                BigDecimal distributionAmount = orderGift.getInitAmount().multiply(new BigDecimal(customerDistribution.getDistributionRate())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                // 分销用户设置分销金额
                orderGift.setDistributionAmount(distributionAmount);
                orderGift.setFinalAmount(orderGift.getInitAmount().subtract(distributionAmount));
            }
        }

        if(orderGift.getGiftId() != null){
            // 店员礼物埋点
            EmployeeGift employeeGift = new EmployeeGift();
            employeeGift.setEmployeeId(orderGift.getEmployeeUserId());
            employeeGift.setGiftId(orderGift.getGiftId());
            EmployeeGift eg = employeeGiftService.selectEmployeeGiftInfo(employeeGift);
            if(StringUtils.isNotNull(eg)){
                // 已收到过，数量加1
                eg.setGiftNum(eg.getGiftNum() + orderGift.getGiftNum());
                employeeGiftService.updateEmployeeGift(eg);
            }else{
                employeeGift.setGiftId(orderGift.getGiftId());
                employeeGift.setEmployeeId(orderGift.getEmployeeUserId());
                employeeGift.setGiftNum(orderGift.getGiftNum());
                employeeGift.setShopId(orderGift.getShopId());
                employeeGiftService.insertEmployeeGift(employeeGift);
            }
        }

        orderGift.setPayStatus(UserConstants.PAY_STATUS_PAID);
        // 更新信息
        orderGiftMapper.updateOrderGift(orderGift);
        // 店员财务记录
        employeeFinanceCenter(orderGift, UserConstants.FINANCE_GIFT);;
        // 客户财务记录
        customerFinanceCenter(orderGift, UserConstants.FINANCE_GIFT);
        // 店员数据埋点统计
        employeeStaticService.updateUserGift(orderGift.getEmployeeUserId(), orderGift.getEmployeeGetAmount());
        // 客户数据统计
        customerStaticService.updateUserGift(orderGift.getOrderUserId(), orderGift.getActualAmount());
        // 微信通知
        wxOAuthchatService.messageReward(orderGift.getOrderNo());
    }

    // 客户财务记录
    public void customerFinanceCenter(OrderGift orderGift, String financeType){
        CustomerFinance customerFinance = new CustomerFinance();
        customerFinance.setUserId(orderGift.getOrderUserId());
        customerFinance.setFinanceType(financeType);
        customerFinance.setOrderNo(orderGift.getOrderNo());
        customerFinance.setAmount(orderGift.getActualAmount());
        customerFinance.setShopId(orderGift.getShopId());
        customerFinanceService.insertCustomerFinance(customerFinance);
    }

    // 店员财务记录
    public void employeeFinanceCenter(OrderGift orderGift, String financeType){
        // 客户数据埋点统计
        EmployeeFinance employeeFinance = new EmployeeFinance();
        employeeFinance.setUserId(orderGift.getEmployeeUserId());
        employeeFinance.setFinanceType(financeType);
        employeeFinance.setOrderNo(orderGift.getOrderNo());
        employeeFinance.setAmount(orderGift.getEmployeeGetAmount());
        employeeFinance.setShopId(orderGift.getShopId());
        employeeFinanceService.insertEmployeeFinance(employeeFinance);
    }

    /**
     * 修改保存礼物订单信息
     *
     * @param orderGift 礼物订单信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateOrderGift(OrderGift orderGift)
    {
        return orderGiftMapper.updateOrderGift(orderGift);
    }

    /**
     * 修改礼物订单支付状态
     *
     * @param orderGift 礼物订单信息
     * @return 结果
     */
    @Override
    public int updateOrderGiftPayStatus(OrderGift orderGift)
    {
        return orderGiftMapper.updateOrderGift(orderGift);
    }

    /**
     * 通过礼物订单编号删除礼物订单
     *
     * @param orderNo 礼物订单编号
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteOrderGiftByOrderNo(String orderNo)
    {
        return orderGiftMapper.deleteOrderGiftByOrderNo(orderNo);
    }

    /**
     * 批量删除礼物订单信息
     *
     * @param orderNos 需要删除的礼物订单编号
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteOrderGiftByOrderNos(String[] orderNos)
    {
        return orderGiftMapper.deleteOrderGiftByOrderNos(orderNos);
    }
}
